package com.tanhua.server.interceptor;


import com.tanhua.model.domain.User;
import com.tanhua.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor extends HandlerInterceptorAdapter {

    /**
     * 资源拦截前的业务
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token数据
        String token = request.getHeader("Authorization");
        //判断token是否合法
        /*boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken){
            //不合法直接拦截,并放回状态码401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }*/
        //解析token
        Claims claims = JwtUtils.getClaims(token);
        //获取claims对象中的用户id和mobile并存入ThreadLocal中
        Integer id = (Integer) claims.get("id");
        String mobile = (String) claims.get("mobile");
        //封装用户数据
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);
        //存入ThreadLocal中
        UserHolder.set(user);
        //放行
        return true;
    }

    /**
     * 请求拦截完后删除ThreadLocal中的用户信息
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserHolder.remove();
    }
}
